import * as THREE from 'three';
import * as dat from 'dat.gui';

export function init08(width, height) {
  // 初始化场景、相机、渲染器
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 1000);
  const renderer = new THREE.WebGLRenderer();
  renderer.setClearColor(new THREE.Color(0x000000));
  renderer.setSize(width, height);
  // 阴影
  renderer.shadowMap.enabled = true;

  // 将平面添加到场景中
  const planeGeometry = new THREE.PlaneGeometry(60, 20);
  const planeMaterial = new THREE.MeshLambertMaterial({
    color: 0xffffff
  });
  const plane = new THREE.Mesh(planeGeometry, planeMaterial);
  plane.rotation.x = -0.5 * Math.PI;
  plane.position.set(15, 0, 0);
  // 接收阴影
  plane.receiveShadow = true;
  scene.add(plane);

  // 将方块添加到场景中
  const cubeGemoetry = new THREE.BoxGeometry(4, 4, 4);
  const cubeMaterial = new THREE.MeshLambertMaterial({
    color: 0xff0000
  });
  const cube = new THREE.Mesh(cubeGemoetry, cubeMaterial);
  cube.position.set(-4, 3, 0);
  // 接收阴影
  cube.castShadow = true;
  scene.add(cube);

  // 将球体添加到场景中
  const sphereCeometry = new THREE.SphereGeometry(4, 20, 20);
  const sphereMterial = new THREE.MeshLambertMaterial({
    color: 0x7777ff
  });
  const sphere = new THREE.Mesh(sphereCeometry, sphereMterial);
  sphere.position.set(20, 4, 2);
  // 接收阴影
  sphere.castShadow = true;
  scene.add(sphere);

  // 将相机定位并指向场景的中心
  camera.position.set(-30, 40, 30);
  camera.lookAt(scene.position);

  // 将光源添加到场景中
  const spotLight = new THREE.SpotLight(0xffffff);
  spotLight.position.set(-40, 40, -15);
  spotLight.castShadow = true;
  spotLight.shadow.mapSize = new THREE.Vector2(1024, 1024);
  spotLight.shadow.camera.far = 130;
  spotLight.shadow.camera.near = 40;
  scene.add(spotLight);

  // 将呈现器的输出添加到 html 元素中
  document.getElementById('webgl-output').appendChild(renderer.domElement);

  // 变量控制器对象
  const controls = new (function() {
    this.rotationSpeed = 0.02;
    this.bouncingSpeed = 0.03;
  })();

  // 变量可视化调整
  const gui = new dat.GUI();
  gui.add(controls, 'rotationSpeed', 0, 0.5);
  gui.add(controls, 'bouncingSpeed', 0, 0.5);

  // 浏览器大小自适应
  window.addEventListener('resize', onResize, false);

  function onResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(width, height);
  }

  let step = 0;

  function render() {
    // 旋转立方体
    cube.rotation.x += controls.rotationSpeed;
    cube.rotation.y += controls.rotationSpeed;
    cube.rotation.z += controls.rotationSpeed;
    // 弹跳球
    step += controls.bouncingSpeed;
    sphere.position.x = 20 + 10 * Math.cos(step);
    sphere.position.y = 2 + 1 * Math.abs(Math.sin(step));
    // 渲染场景
    renderer.render(scene, camera);
    requestAnimationFrame(render);
  }

  render();
}
